//封装mongodb接口

//1.引入mongodb
const { MongoClient } = require("mongodb");
/*
  {
    MongoClient：{
      connect(url,cb) {
        //获取你传入的路径帮你连接mongodb 大数据库
        //连接成功 返回连接对象 client。连接失败，返回err
      }
    }
  }

  let mongo = require("mongodb");
  let MongoClient = mongo.MongoClient;
  MongoClient.connect(url,(err, client) => {
    client:连接对象
    //client 对象里面有个db()连接具体小数据库(仓库)
    let db = client.db('h52002');
    //得到db数据库仓库后，得到集合
    let col = db.collection('users');
    //CRUD
    client.close()
  });
*/
let config = require("../config.json");

//2.连接数据库
let url = config.DBurl;
let dbName = config.DBname2;

//3.封装接口

//连接数据库函数，调用会得到一个promise对象
function connect(colName) {
  return new Promise((success, fail) => {
    MongoClient.connect(url, (err, client) => {
      if (err) fail(err); //如果有失败，就返回失败信息
      //成功的话就连接数据库
      let db = client.db(dbName);
      //连接集合
      let col = db.collection(colName);

      success({ client, col });
    });
  });
}

//插入数据接口
async function create(colname, datalist) {
  //datalist是数组
  let result = {};

  let { client, col } = await connect(colname); //连接数据库

  try {
    //插入数据
    let data = await col.insertMany(datalist);

    //判断是否插入成功
    if (data.insertedCount) {
      result = {
        code: 1,
        message: "插入成功",
      };
    } else {
      result = {
        code: 0,
        message: "插入失败",
      };
    }
  } catch (err) {
    result = {
      code: 0,
      message: "服务器异常",
    };
  }

  client.close(); //关闭数据库
  return result; //返回数据
}

//测试接口
// let song = [
//   {
//     id: 6,
//     name: "流星蝴蝶剑6666",
//   },
//   {
//     id: 7,
//     name: "王祖贤&梁朝伟666",
//   },
// ];

// let res = create('songs',song);
// res.then((r) => {
//   console.log(r);
// });
// console.log(res);

//删除数据
async function remove(colname, query) {
  //连接数据库
  let { client, col } = await connect(colname);
  let result = {};

  try {
    //删除数据
    let data = await col.deleteMany(query);
    if (data.deletedCount) {
      result = {
        code: 1,
        message: "删除成功",
      };
    } else {
      result = {
        code: 0,
        message: "没有该数据",
      };
    }
  } catch (err) {
    result = {
      code: 0,
      message: "服务器异常",
    };
  }

  client.close();
  return result;
}

//测试接口
// let res = remove("songs", { name: "天后" });
// res.then((r) => {
//   console.log(r);
// });

//修改数据
async function update(colname, query, newdata) {
  //连接数据库
  let { client, col } = await connect(colname);
  let result = {};
  try {
    let data = await col.updateMany(query, {
      $set: newdata,
    }); //修改数据：query：条件，对象格式;newdata：数据，对象格式
    if (data.modifiedCount) {
      result = {
        code: 1,
        message: "修改成功",
      };
    } else {
      result = {
        code: 0,
        message: "修改失败",
      };
    }
  } catch (err) {
    result = {
      code: 0,
      message: "服务器异常",
    };
  }

  client.close(); //关闭数据库
  return result;
}

//测试update()
// let res = update(
//   "songs",
//   { id: 2 },
//   {
//     $set: {
//       name: "甜蜜蜜",
//     },
//   }
// );
// res.then((r) => {
//   console.log(r);
// });

//查询数据:查找“红色连衣裙”，价格从高到低，第一页50条数据
async function find(colname, opt) {
  //opt配置参数
  //连接数据库
  let { client, col } = await connect(colname);
  let defaultOpt = {
    //设置默认值
    page: 1,
    pagesize: 10,
    sortquery: {}, //不排序
    findquery: {}, //不查询数据
  };

  //替补方案
  Object.assign(defaultOpt, opt); //defaultOpt的数据是最全的

  let result = {};
  try {
    let index = (defaultOpt.page - 1) * defaultOpt.pagesize;
    let data = await col
      .find(defaultOpt.findquery)
      .limit(defaultOpt.pagesize)
      .skip(index)
      .sort(defaultOpt.sortquery)
      .toArray();
    if (data.length) {
      result = {
        code: 1,
        message: "查询成功",
        data,
      };
    } else {
      result = {
        code: 0,
        message: "查询失败",
      };
    }
  } catch (err) {
    result = {
      code: 0,
      message: "服务器异常",
    };
  }

  client.close();
  return result;
}

//低配
async function lowfind(colname, query) {
  //opt配置参数
  //连接数据库
  let { client, col } = await connect(colname);

  let result = {};
  try {
    let data = await col.find(query).toArray();
    if (data.length) {
      result = {
        code: 1,
        message: "查询成功",
        data,
      };
    } else {
      result = {
        code: 0,
        message: "查询失败",
      };
    }
  } catch (err) {
    result = {
      code: 0,
      message: "服务器异常",
    };
  }

  client.close();
  return result;
}

// let res = find("songs", {
//   page: 1, //必填:页码
//   pagesize: 10, //必填:每页多少条
//   findquery: { name: "兄弟啊" }, //选填；默认不查询
//   sortquery: { id: -1 }, //选填;默认不排序
// });

// res.then((r) => {
//   console.log(r);
// });

//替补方案:踢足球:主角；替补：备胎

// let obj = {
//   name: "吴彦祖", //主角：配置参数
//   age: 50,
// };

// let obj2 = {
//   name: "吴亦凡", //备胎:默认参数
// };

// let newobj = Object.assign({}, obj2, obj); //合并对象
// console.log(newobj);

module.exports = {
  create,
  remove,
  update,
  find,
  lowfind,
};
